package kino.timeevent;

import com.sun.management.OperatingSystemMXBean;
import kino.server.KinoServerRuntime;

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.text.DecimalFormat;

/**
 * serverCron时间事件
 */
public class ServerCronTimeEvent extends TimeEvent{

    private static final String MB = "M";

    private static final Integer TO_MB = 1024 * 1024;

    public ServerCronTimeEvent(Long lastExecutionEventTime, Long interval) {
        super(lastExecutionEventTime, interval);
    }

    public ServerCronTimeEvent(Long interval) {
        super(interval);
    }

    @Override
    void doTimeEventExecute() {
        // 服务端运行状态
        KinoServerRuntime kinoServerRuntime = KinoServerRuntime.getInstance();
        // 获取当前程序的内存占用
        this.getMemory(kinoServerRuntime);
    }

    public void getMemory(KinoServerRuntime kinoServerRuntime) {
        try {
            Runtime runtime = Runtime.getRuntime();
            // java虚拟机中的内存总量，可用内存空间 单位为byte，默认为系统的1/64
            long totalMemory = runtime.totalMemory();
            // java 虚拟机中的空闲内存量 空闲空间 单位byte， 默认为系统的1/4
            long freeMemory = runtime.freeMemory();
            // 设置内存使用
            kinoServerRuntime.setUsedMemory((int)(totalMemory - freeMemory));
            kinoServerRuntime.setUsedMemoryHuman((int)(totalMemory - freeMemory) / TO_MB + MB);
            // 更新峰值内存使用
            if (kinoServerRuntime.getUsedMemoryPeak() == null || kinoServerRuntime.getUsedMemory() > kinoServerRuntime.getUsedMemoryPeak()) {
                kinoServerRuntime.setUsedMemoryPeak(kinoServerRuntime.getUsedMemory());
                kinoServerRuntime.setUsedMemoryPeakHuman(kinoServerRuntime.getUsedMemoryHuman());
            }
        } catch (Exception e) {
            // 空
        }
    }

}
